/**
 * Copyright (C) 2008 Huascar A. Sanchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.gotobject.inject.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.io.IOException;
import java.io.InputStream;

/**
 * A {@link Utils utility class} where common functions dealing with the {@code Quickmix} api
 * will be placed.
 *
 * @author huascar.sanchez@gmail.com (Huascar A. Sanchez)
 */
public class Utils {
    private Utils(){
        // do nothing yet
    }

    /**
	 * casting the tiger way.
	 * @param me
	 * 		the object we are casting.
	 * @param to
	 * 		the targetted casting class.
	 * @return the casted object.
     */
    public static <T, E extends T> E cast(T me, Class<? extends E> to){
        return to.cast(me);
    }


    public static <K, V> Map<K, V> newHashMap(){
        return new HashMap<K, V>();
    }

    public static Properties loadProperties(Class<?> enclosingClass, String path) throws IOException {
        final InputStream is    = enclosingClass.getResourceAsStream(path);
        final Properties props  = new Properties();
        final Properties result = new Properties();
        try {
            props.load(is);
            for(Map.Entry<?, ?> eachEntry : props.entrySet()){
				final String key    = cast(eachEntry.getKey(), String.class);
				final String value  = cast(eachEntry.getValue(), String.class);

				if(key.indexOf("image") != -1){
                    final String newPath = enclosingClass.getResource(value).getFile();
                    result.setProperty(key, newPath);
                } else if(key.indexOf("file") != -1){
                    final String newPath = enclosingClass.getResource(value).getFile();
                    result.setProperty(key, newPath);
                } else {
                    result.setProperty(key, value);
                }
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if(is  != null){
                is.close();
            }
        }
        return result;
    }
}
